﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Ext.Net;

public partial class SYS_POPEDOM_BatchUserRole : BasePage
{
    private static string clickNodeId = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BuildTreeRoot(TreePanel1);
            BuildTreeRoot(TreePanel2);
        }
    }


    protected void OnStoreRefreshData(object sender, StoreRefreshDataEventArgs e)
    {
        BindGrid("NodeClick");
    }

    //单击树节点


    [DirectMethod]
    public void NodeClick(string NodeId)
    {
        clickNodeId = NodeId;
        GridPanel1.Reload();
        GridPanel3.Reload();
    }

    protected void extBtn_Find_Click(object sender, DirectEventArgs e)
    {
        BindGrid("Find_Click");
    }



    //加载列表
    private void BindGrid(string searchType)
    {
        DataTable GridData = null;
        if (searchType == "Find_Click")
        {

            string sql = string.Format(@"with cte as
(
    select * from( select a.*,b.DEPT_NAME PARENT_NAME from SYS_DEPT a LEFT join SYS_DEPT b on b.DEPT_ID = a.PARENT_ID ) t
    where rtrim(ltrim(DEPT_ID))='{0}' 
    union all
    select d.*,c.DEPT_NAME PARENT_NAME from cte c inner join SYS_DEPT d
    on c.DEPT_ID = d.PARENT_ID
)
select n.*,m.DEPT_NAME from cte m
inner join SYS_USER n on n.DEPT_ID = m.DEPT_ID 
where n.del_flag=0 and (USER_NAME like '%{1}%' OR USER_ID LIKE '%{1}%' OR USER_PYM LIKE '%{1}%') 
order by display_order
", clickNodeId.Trim(), exttxtf_user_name.Text.Trim());

            GridData = CommonLib.BLL.BS_DATASET_SQL.SqlGetTable(sql);
        }
        else
        {
            GridData = CommonLib.BLL.SYS_USER.GetList(GetQryString(), "display_order").Tables[0];
        }
        this.Store1.DataSource = GridData;
        this.Store1.DataBind();
    }
    private string GetQryString()
    {
        string result = "del_flag=0";
        result += " and dept_id like '" + clickNodeId + "%' ";
        if (exttxtf_user_name.Text != "")
            result += string.Format(" and (USER_NAME like '%{0}%' OR USER_ID LIKE '%{0}%' OR USER_PYM LIKE '%{0}%') ", exttxtf_user_name.Text);
        return result;
    }



    //构建部门树根节点
    private void BuildTreeRoot(TreePanel treePanel)
    {
        DataTable tmpDt = CommonLib.BLL.SYS_DEPT.GetListSub(" dept_id='00' and  del_flag =0 ", "dept_no").Tables[0];
        if (tmpDt.Rows.Count == 1)
        {
            Ext.Net.AsyncTreeNode root = new Ext.Net.AsyncTreeNode();
            root.Text = tmpDt.Rows[0]["dept_name"].ToString();
            root.NodeID = tmpDt.Rows[0]["dept_id"].ToString();
            root.Expanded = true;
            root.IconCls = "no-icon";
            if (tmpDt.Rows[0]["leaf"].ToString() == "0")
                root.Leaf = true;
            root.Draggable = true;
            treePanel.Root.Add(root);
        }
    }


    //加载下属节点
    [DirectMethod]
    public string NodeLoad(string nodeID)
    {
        Ext.Net.TreeNodeCollection nodes = new Ext.Net.TreeNodeCollection();
        if (!string.IsNullOrEmpty(nodeID))
        {
            DataTable TreeData = CommonLib.BLL.SYS_DEPT.GetListSub(" del_flag =0 and ltrim(rtrim(dept_id)) like '" + nodeID.Trim() + "__' ", "dept_no").Tables[0];
            for (int i = 0; i < TreeData.Rows.Count; i++)
            {
                AsyncTreeNode asyncNode = new AsyncTreeNode();
                asyncNode.Text = TreeData.Rows[i]["dept_name"].ToString();
                asyncNode.NodeID = TreeData.Rows[i]["dept_id"].ToString();
                asyncNode.IconCls = "no-icon";
                if (TreeData.Rows[i]["leaf"].ToString() == "0")
                    asyncNode.Leaf = true;
                nodes.Add(asyncNode);
            }
        }
        clickNodeId = nodeID;
        BindGrid("NodeClick");
        return nodes.ToJson();
    }



    #region  以下是弹出窗体代码


    [DirectMethod]
    public string NodeLoadWin(string nodeID,string[] ids)
    {
        Ext.Net.TreeNodeCollection nodes = new Ext.Net.TreeNodeCollection();
        if (!string.IsNullOrEmpty(nodeID))
        {
            DataTable TreeData = CommonLib.BLL.SYS_DEPT.GetListSub(" del_flag =0 and ltrim(rtrim(dept_id)) like '" + nodeID.Trim() + "__' ", "dept_no").Tables[0];
            foreach (DataRow tdr in TreeData.Rows)
            {
                AsyncTreeNode asyncNode = new AsyncTreeNode();
                asyncNode.Text = tdr["dept_name"].ToString();
                asyncNode.NodeID = tdr["dept_id"].ToString();
                asyncNode.IconCls = "no-icon";
                if (tdr["leaf"].ToString() == "0")
                    asyncNode.Leaf = true;
                nodes.Add(asyncNode);
            }

            string where = " creator IN (SELECT su.[USER_ID] FROM SYS_USER su WHERE Charindex(RTRIM('" + BS_LoginDeptId + "'),su.DEPT_ID,0) > 0 ) ";
            DataTable TmpTable = CommonLib.BLL.SYS_DEPT_ROLES.GetList(" ltrim(rtrim(dept_id))='" + nodeID.Trim() + "' and " + where).Tables[0];

            foreach (var hid in ids)
            {
                DataRow tr = TmpTable.Select("MASTER_ID='" + hid + "'").FirstOrDefault();
                if (tr != null)
                    TmpTable.Rows.Remove(tr);
            }
            TmpTable.AcceptChanges();

            foreach (DataRow item in TmpTable.Rows)
            {
                Ext.Net.TreeNode treeNode = new Ext.Net.TreeNode();
                treeNode.Text = item["ROLE_NAME"].ToString();
                treeNode.NodeID = item["MASTER_ID"].ToString();
                treeNode.Leaf = true;
                treeNode.IconCls = "no-icon";
                treeNode.Checked = ThreeStateBool.False;
                nodes.Add(treeNode);
            }
        }
        return nodes.ToJson();
    }


    [DirectMethod]
    public void AddSelectedNodes(string[] ids)
    {
        if (ids.Length == 0)
            return;
        string wSql = string.Join(",", ids);
        DataTable dt = CommonLib.BLL.SYS_DEPT_ROLES.GetList(" MASTER_ID in(" + wSql + ") ", " DEPT_NAME,ROLE_NAME ").Tables[0];
        Store3.DataSource = dt;
        Store3.DataBind();

    }

    [DirectMethod]
    public void SaveData(string[] uids, string[] mids)
    {
        string sqltmp = "  SELECT '{0}' USER_ID,{1} MASTER_ID,'' NOTES ";
        List<string> lst = new List<string>();
        foreach (string uid in uids)
            foreach (string mid in mids)
                lst.Add(string.Format(sqltmp, uid, mid));
        string dsql = string.Join(" UNION ",lst.ToArray());
        string sql = @"INSERT INTO SYS_OPERATOR_ROLE
  select a.* from ( " + dsql + @"
 ) a
 LEFT JOIN  SYS_OPERATOR_ROLE b on a.USER_ID = b.USER_ID AND a.MASTER_ID = b.MASTER_ID
 WHERE b.USER_ID IS NULL ";
        try
        {
            MSSQLDAL.SqlHelper.ExecuteNonQuery(MSSQLDAL.Conn.SqlConnStr, CommandType.Text, sql);
            X.Msg.Alert("提示", "保存成功！").Show();
        }
        catch (Exception ex)
        {
            X.Msg.Alert("提示", "保存失败！</br>" + ex.Message).Show();
        }



    }


    [DirectMethod]
    public string RefreshMenu(string[] ids)
    {
        Ext.Net.TreeNodeCollection nodes = BuildTree(ids, null);
        return nodes.ToJson();
    }

    private Ext.Net.TreeNodeCollection BuildTree(string[] ids,Ext.Net.TreeNodeCollection nodes)
    {
        string where = " creator IN (SELECT su.[USER_ID] FROM SYS_USER su WHERE Charindex(RTRIM('" + BS_LoginDeptId + "'),su.DEPT_ID,0) > 0 ) ";

        if (nodes == null)
        {
            nodes = new Ext.Net.TreeNodeCollection();
        }
        DataTable tmpDt = CommonLib.BLL.SYS_DEPT.GetListSub(" dept_id='00' and  del_flag =0 ", "dept_id").Tables[0];
        if (tmpDt.Rows.Count == 1)
        {
            Ext.Net.TreeNode root = new Ext.Net.TreeNode();
            root.Text = tmpDt.Rows[0]["dept_name"].ToString();
            root.NodeID = tmpDt.Rows[0]["dept_id"].ToString();
            root.Expanded = true;
            root.IconCls = "no-icon";
            if (tmpDt.Rows[0]["leaf"].ToString() == "0")
                root.Leaf = true;
            root.Draggable = true;
            nodes.Add(root);
            DataTable TreeData = CommonLib.BLL.SYS_DEPT.GetListSub(" del_flag =0 and ltrim(rtrim(dept_id)) like '" + tmpDt.Rows[0]["dept_id"].ToString().Trim() + "__' ", "dept_no").Tables[0];
            DataTable tmpT = null;
            foreach (DataRow dr in TreeData.Rows)
            {
                if (dr["leaf"].ToString() == "0")
                {

                    tmpT = CommonLib.BLL.SYS_DEPT_ROLES.GetList(" ltrim(rtrim(dept_id))='" + dr["dept_id"].ToString().Trim() + "' and " + where).Tables[0];
                    if (tmpT.Rows.Count > 0)
                    {
                        dr.BeginEdit();
                        dr["leaf"] = 1;
                        dr.EndEdit();
                        TreeData.AcceptChanges();
                    }
                }
            }

            for (int i = 0; i < TreeData.Rows.Count; i++)
            {
                AsyncTreeNode asyncNode = new AsyncTreeNode();
                asyncNode.Text = TreeData.Rows[i]["dept_name"].ToString();
                asyncNode.NodeID = TreeData.Rows[i]["dept_id"].ToString();
                asyncNode.IconCls = "no-icon";
                if (TreeData.Rows[i]["leaf"].ToString() == "0")
                    asyncNode.Leaf = true;
                root.Nodes.Add(asyncNode);
            }
            DataTable TmpTable = CommonLib.BLL.SYS_DEPT_ROLES.GetList(" ltrim(rtrim(dept_id))='" + tmpDt.Rows[0]["dept_id"].ToString().Trim() + "' and " + where).Tables[0];
            foreach (var hid in ids)
            {
                DataRow tr = TmpTable.Select("MASTER_ID='" + hid + "'").FirstOrDefault();
                if (tr != null)
                    TmpTable.Rows.Remove(tr);
            }
            
            TmpTable.AcceptChanges();
            for (int j = 0; j < TmpTable.Rows.Count; j++)
            {
                Ext.Net.TreeNode treeNode = new Ext.Net.TreeNode();
                treeNode.Text = TmpTable.Rows[j]["ROLE_NAME"].ToString();
                treeNode.NodeID = TmpTable.Rows[j]["MASTER_ID"].ToString();
                treeNode.Leaf = true;
                treeNode.IconCls = "no-icon";
                treeNode.Checked = ThreeStateBool.False;
                root.Nodes.Add(treeNode);
            }
        }
        return nodes;
    }
    #endregion

}
